package com.xiaobao.coalproperty.module.login.view;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.gson.Gson;
import com.xiaobao.coalproperty.MainActivity;
import com.xiaobao.coalproperty.R;
import com.xiaobao.coalproperty.module.login.model.entity.LoginEntity;
import com.xiaobao.coalproperty.other.base.BaseActivity;
import com.xiaobao.coalproperty.other.constant.StringConstant;
import com.xiaobao.coalproperty.other.constant.UrlConstant;
import com.xiaobao.coalproperty.other.util.HttpHelperUtils;
import com.xiaobao.coalproperty.other.util.SharedPreferencesUtils;
import com.xiaobao.coalproperty.other.util.UserHelperUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import butterknife.BindView;
import okhttp3.Call;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.login_phone)
    EditText edtPhone;
    @BindView(R.id.login_pwd)
    EditText edtPwd;
    @BindView(R.id.login_new_user)
    LinearLayout llNewUser;
    @BindView(R.id.login_forget)
    LinearLayout llForget;
    @BindView(R.id.login_login)
    Button btnLogin;
    @BindView(R.id.login_wx)
    ImageView ivWx;

    @Override
    protected int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setTitle("登录");
        showLeft(false);
        edtPhone.setCursorVisible(false);
        edtPwd.setCursorVisible(false);
        edtPhone.setOnClickListener(mOnClickListener);
        edtPwd.setOnClickListener(mOnClickListener);
        llNewUser.setOnClickListener(mOnClickListener);
        llForget.setOnClickListener(mOnClickListener);
        ivWx.setOnClickListener(mOnClickListener);
        btnLogin.setOnClickListener(mOnClickListener);

        if (!TextUtils.isEmpty(UserHelperUtils.getInstance().getHashId())) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        initPer();
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.login_new_user:
                    startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                    break;
                case R.id.login_forget:
                    startActivity(new Intent(LoginActivity.this, ForgetActivity.class));
                    break;
                case R.id.login_wx:
                    showToast("微信登录暂不开放");
                    break;
                case R.id.login_login:
                    if (!isMobileNO(edtPhone.getText().toString())) {
                        showToast("手机号码格式不正确");
                        return;
                    }
                    if (TextUtils.isEmpty(edtPwd.getText().toString())) {
                        showToast("密码不能为空");
                        return;
                    }
                    login();
                    break;
                case R.id.login_phone:
                    edtPhone.setCursorVisible(true);
                    edtPhone.setFocusableInTouchMode(true);
                    edtPhone.requestFocus();
                    break;
                case R.id.login_pwd:
                    edtPwd.setCursorVisible(true);
                    edtPwd.setFocusableInTouchMode(true);
                    edtPwd.requestFocus();
                    break;
            }
        }
    };

    private void login() {
        OkHttpUtils.post().url(UrlConstant.URL_LOGIN)
                .params(HttpHelperUtils.getInstance().loginParams(edtPhone.getText().toString(), edtPwd.getText().toString()))
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    LoginEntity entity = new Gson().fromJson(response, LoginEntity.class);
                    if (entity.getCode() == 0) {
                        loginSuccess(entity);
                        return;
                    }
                    showToast(entity.getMsg());
                } catch (Exception e) {
                }
            }
        });
    }

    private void loginSuccess(LoginEntity entity) {
        UserHelperUtils.getInstance().clearUser();
        SharedPreferencesUtils.getInstance().put(StringConstant.USER_UID, entity.getData().getUid() + "");
        SharedPreferencesUtils.getInstance().put(StringConstant.USER_HASHID, entity.getData().getHashid());
        SharedPreferencesUtils.getInstance().put(StringConstant.USER_FACE, entity.getData().getFace());
        SharedPreferencesUtils.getInstance().put(StringConstant.USER_NICKNAME, entity.getData().getNickname());
        SharedPreferencesUtils.getInstance().put(StringConstant.USER_PHONE, entity.getData().getPhone());
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        finish();
    }

    /*权限判断*/
    private void initPer() {
        String[] per = new String[]{
                Manifest.permission.CALL_PHONE
        };
        PermissionsUtil.requestPermission(this, new PermissionListener() {
            @Override
            public void permissionGranted(@NonNull String[] permissions) {
            }

            @Override
            public void permissionDenied(@NonNull String[] permissions) {
            }
        }, per, false, null);
    }

    public boolean isMobileNO(String mobileNums) {

        String telRegex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }
}
